<script setup>
import Drawer from '@/components/common/Drawer.vue'
import FloatButtonGroup from '@/components/common/FloatButtonGroup.vue'

import { ref, inject, onMounted, watch, provide } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import documentApi from '@/apis/document'

const isSmallPage = inject('isSmallPage')
const route = useRoute()
const router = useRouter()

const scrollbarRef = ref(null)
const drawerRef = ref(null)
const showToTopBtn = ref(false)

const list = ref([])
const detail = ref({})

const getList = async () => {
  const { data: paginate } = await documentApi.list('tutorial')
  list.value = paginate.data
}

const gotoFirst = async () => {
  await router.replace({
    name: 'documentHelpRead',
    params: { id: list.value[0].id },
  })
}

const handleScroll = ({ scrollTop }) => {
  showToTopBtn.value = scrollTop > 300
}

const scrollToTop = () => {
  if (scrollbarRef.value)
    scrollbarRef.value.scrollTo({
      top: 0,
      behavior: 'smooth',
    })
}

const toggleDrawer = () => {
  drawerRef.value?.toggle()
}

watch(
  () => list.value.length && route.name === 'documentHelp',
  async (val) => {
    if (val) await gotoFirst() //访问第一条
  }
)

onMounted(getList)

provide('list', list)
provide('drawerRef', drawerRef)
</script>
<template>
  <div class="sm:flex h-full">
    <Drawer ref="drawerRef" width="w-64">
      <el-scrollbar class="subnav p-3">
        <h2 class="subnav-title font-bold mb-1">
          <span>教程</span>
        </h2>
        <template v-for="item in list">
          <RouterLink
            :to="{ name: 'documentHelpRead', params: { id: item.id } }"
            :class="{ 'subnav-item': true, active: parseInt(route.params.id) === item.id }"
            :title="item.title"
          >
            <span class="ml-2 truncate"> ∙ {{ item.title }}</span>
          </RouterLink>
        </template>
      </el-scrollbar>
    </Drawer>
    <el-scrollbar ref="scrollbarRef" class="w-full h-full lg:px-5" @scroll="handleScroll">
      <RouterView />
    </el-scrollbar>
    <FloatButtonGroup :bottom="40">
      <FloatButton @click="scrollToTop" v-if="showToTopBtn" icon="caret-up" />
      <FloatButton @click="toggleDrawer" v-if="isSmallPage" icon="bars" />
    </FloatButtonGroup>
  </div>
</template>

<style scoped>
.subnav {
  @apply flex flex-col w-full min-h-80;
}

.subnav-item {
  @apply flex items-center relative py-1 mb-1 cursor-pointer rounded space-x-1 text-sm
  hover:bg-[--el-fill-color-light];
}

.subnav-item.active {
  @apply bg-[--el-fill-color-dark];
}
</style>
